/*
 * Create:      柿子
 * CreateDate:  2022/11/21
 * Describe：   住院病历信息（新范例病例样式）
 * */
import React from 'react';
import { Tree, Input, Icon, Modal, message, Popconfirm, Form, Tabs, Spin, Button, Card, Tooltip } from 'antd';
import { $http } from 'containers/config/https';
import { httpConfig } from 'containers/config/httpConfig';
import { Util } from 'tools/index';
import store from 'store';
import PublicModalFormHooks from 'pages/common/PublicModalFormHooks';
import AddSampleTemplate from './AddSampleTemplate.jsx'; // 保存范例病历
import CaseInformationPageTabs from './CaseInformationPageTabs.jsx';
import ElectronicCaseTemplate from 'pages/common/ElectronicCaseTemplate.jsx';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import MedicalRecordTemplateSelection from './MedicalRecordTemplateSelection.jsx'; // 加载病历模板
import '../../pharmacy/outpha/style/outpha.less';
import '../style/CMOrderSave.less';

const { TabPane } = Tabs;
const { TreeNode } = Tree;
const { confirm } = Modal;
let timer = null;

class CaseInformationPageExampleCase extends React.Component {
  constructor(props) {
    super(props)
    var userData = React.$getSessionData();
    var recordData = React.$getSessionData('patientData');
    var titleData = React.$getSessionData('titleData');
    this.newTabIndex = 0;
    this.state = {
      recordData,
      userData,
      titleData,
      expandedKeys: [],
      selectedKeys: [],
      treeSelectData: {},
      treeData: [],
      templateName: '',
      autoExpandParent: true,
      modalTemplateData: [],
      oldModalTemplateData: [],
      modalRowData: {},
      isVResize: false,
      hNum: 100,
      vNum: 960,
      hNumLimit: 30,
      vNumLimit: 30,
      tableData: [],
      columns: [],
      total: 0,
      page: 1,
      pageSize: 10,
      showValidateResult: 'show', // 是否显示错误下拉框
      prModal: 'show', // modal名称 模板 知识库
      templateTree: '',
      spinLoading: false, // 全局loading
      defaultMillisecond: 0, // 默认倒计时毫秒数
      isDeleteRecord: false, // 是否可以删除病历
      loadingTitle: '', // loading加载描述
      isUnlocking: true,
      recordDataID: '', // 病历记录数据ID
      historyAdmID: '',
      contextMenuData: {},
      menuVisible: false,
      panes: [],
      recordActiveKey: '',
      isHasDeletedRecord: false,
      templateID: undefined,
      hideTabs: false,
      templateParams: [],
      EMRQCFlag: 'N',
      qualityControlFormData: [], // 质控表单
      copyQualityControlFormData: [],
      qualityControlRowData: {},
      oualityControlType: 'add'
    }
    this.resizeOffsetInfo = {
      clientTop: 0,
      clientLeft: 0
    };
    this.leftHeight = 0;
    this.containerWidth = 0;
    this.columns = [{
      title: '序号',
      dataIndex: 'key',
      key: '1',
      width: '50px',
      align: 'center'
    }, {
      title: '模板名称',
      dataIndex: 'descripts',
      key: '2',
      width: '300px',
      align: 'center'
    }, {
      title: '模板版本号',
      dataIndex: 'releaseVersion',
      key: '3',
      width: '100px',
      align: 'center'
    }]
  }

  componentDidMount() {
    let _this = this;
    this.props && this.props.onRef && this.props.onRef(this);
    this.props.initTemplate !== 'N' && this.getDefaultTemplate(); // 设置默认模板
    this.initResizeInfo();
    this.getChineseAndEnglishData();
    window.onresize = function () {
      setTimeout(function () {
        _this.initResizeInfo()
      }, 200);
    }
    this.getTreeData('patientRecords');
    this.props && this.props.onRef && this.props.onRef(this);
    window.sessionStorage.setItem('showMessagePopUp', 'N');
    document.addEventListener('click', this.handleClick)
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    //该方法内禁止访问this
    if (nextProps.historyAdmID !== prevState.historyAdmID) {
      //通过对比nextProps和prevState，返回一个用于更新状态的对象
      return true
    }
    //不需要更新状态，返回null
    return null
  }

  componentDidUpdate() {
    // 做一些需要this.props的事
    if (this.props.historyAdmID && (this.props.historyAdmID !== this.state.historyAdmID) && this.props.isDidUpdate && this.props.isDidUpdate === 'Y') {
      this.setState({ historyAdmID: this.props.historyAdmID }, () => {
        this.props.initTemplate !== 'N' && this.getDefaultTemplate(); // 设置默认模板
        this.getTreeData('patientRecords');
      })
    }
  }

  componentWillUnmount() {
    this.handleClearComponentInformation();
    // 组件销毁前将静止让setState修改state的状态
    this.setState = (state, callback) => { return; }
  }

  // 切换病人更新相关数据
  loadPatientMsg = () => {
    this.setState({
      recordData: React.$getSessionData('patientData'),
      titleData: React.$getSessionData('titleData'),
      panes: []
    }, () => {
      this.getDefaultTemplate(); // 设置默认模板
      this.getTreeData('patientRecords');
    })
  }

  // 组件销毁时清除组件信息
  handleClearComponentInformation = () => {
    let { panes } = this.state;
    if (panes && panes.length > 0) {
      for (var i = 0; i < panes.length; i++) {
        // 关闭当前组件前解锁所有打开的病历
        let eMRRecordID = panes[i] && panes[i].modalRowData && panes[i].modalRowData.patEMRRecordID ? panes[i].modalRowData.patEMRRecordID : '';
        if (eMRRecordID && this.props.isOperable !== 'Y') {
          this.jqAjax(eMRRecordID, (res) => {
            console.log(res)
          })
        }
      }
    }
    window.onresize = null;
    window.sessionStorage.setItem('showMessagePopUp', 'Y');
    document.removeEventListener('click', this.handleClick)
    if (timer) {
      clearInterval(timer);
      timer = null;
    }
  }

  handleClick = () => {
    const { menuVisible } = this.state
    if (menuVisible) {
      this.setState({ menuVisible: false })
    }
  };

  // 同步请求 -- 解锁
  jqAjax = (eMRRecordID, success, error) => {
    if (window && window.$ && window.$.ajax) {
      let userData = React.$getSessionData();
      if (!(eMRRecordID && userData && userData.userID)) {
        return;
      }
      let url = httpConfig.ipDeault + httpConfig.urlAddress;
      let json = {
        params: [{
          patEMRRecordID: eMRRecordID,
        }]
      }
      let formData = Object.assign({}, json);
      let windowHost = window.location && window.location.protocol && window.location.host ? (window.location.protocol + '//' + window.location.host) : (window.location && window.location.origin ? window.location.origin : '');
      windowHost = windowHost + '/bdhealth/';
      // 判断是否是本地，如果是本地的话取https配置地址，线上则取地址栏地址 （内外网）
      url = windowHost && windowHost.indexOf('localhost') !== -1 ? url : windowHost;
      formData.code = '06050015';
      if (userData) {
        let ip = React.$getSessionData('ipConfig');
        formData.session = [{
          userID: userData.userID || '',
          locID: userData.locID || '',
          groupID: userData.groupID || '',
          hospID: userData.hospID || '',
          sessionID: userData.sessionID || '',
          hostName: ip?.hostName || '',
          ipv4: ip?.ipv4 || '',
          ipv6: ip?.ipv6 || '',
          mac: ip?.mac || '',
        }]
      }
      $.ajax({
        type: 'post',                          //请求方式
        url,     //请求地址
        data: JSON.stringify(formData),                         //发送的数据，这里是json对象
        dataType: 'json',                      //数据类型
        // contentType: 'application/json;charset=utf-8',
        async: false,
        success: function (data) {
          success && success(data);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          // console.log(XMLHttpRequest, textStatus, errorThrown)
          error && error(errorThrown);
        },
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
          'Authorization': httpConfig.authorizationToken,
          'Access-Control-Allow-Origin': httpConfig.ipDeault
        },
      });
    }
  }

  // 获取中英文数据
  getChineseAndEnglishData = () => {
    let { userData } = this.state;
    let data = {
      params: [{
        compontName: 'CaseInformationPage',
        type: 'C',
        reactCode: ['CaseInformationPage']
      }]
    }
    $http.post('urlDeault', this, {
      code: '01040073',
      data: data,
      success: (res) => {
        if (+res.errorCode === 0) {
          var totalWidth = 0;
          let arr = res.result.C && res.result.C.map((item, index) => {
            return {
              ...item,
              key: index,
              widthNum: parseInt(item.width),
              title: <div key={index} onDoubleClick={() => this.mainColumnRef.onOpenModel()}>{userData.language == 'EN' ? (item && item.enDescripts ? item.enDescripts : item.title) : item.title}</div>,
            }
          });
          let filterArr = arr.filter(function (item) { return item.display === 'Y' });
          let obj = {
            title: userData.language == 'EN' ? 'Operation' : '操作',
            key: 14,
            align: 'center',
            width: '80px',
            fixed: 'right',
            widthNum: 80,
            render: (text, record) => (
              <span>
                <Icon type='delete' style={{ color: 'rgba(240,65,52,1)' }}></Icon>
                <Popconfirm title='删除不可恢复，你确定要删除吗?' onConfirm={() => this.handleDelete(record)} >
                  <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
                </Popconfirm>
              </span>
            ),
          };
          filterArr.push(obj);
          for (var i = 0; i < filterArr.length; i++) {
            totalWidth += filterArr[i].widthNum;
          }
          this.setState({
            // columns: filterArr,
            // totalWidth,
            localeProvider: userData.language == 'EN' ? res.result.language.EN : res.result.language.CN
          })
        }
      }
    })
  }

  onMainColumnRef = ref => {
    this.mainColumnRef = ref;
  }

  //国际化
  setMessage = (name, message, defaultTitle) => {
    return this.state.localeProvider && this.state.localeProvider[name] ? this.state.localeProvider[name][message] : defaultTitle
  }

  handleDelete = record => {
    console.log(record)
  }

  // 获取板分组科室下默认模板
  getDefaultTemplate = () => {
    let { recordData, userData } = this.state;
    let data = {
      params: [{
        admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ''),
        admLanguage: userData && userData.admLanguage ? userData.admLanguage : 'CN',
      }]
    }
    $http.post('urlS', this, {
      code: '06010094',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let dataAry = res.result.dataAry;
          let defaultMillisecond = res.result && res.result.autoSaveTime ? Number(res.result.autoSaveTime) : 0;
          let maxOpenTablePanel = res.result && res.result.MaxOpenTablePanel ? Number(res.result.MaxOpenTablePanel) : 5;
          if (!(dataAry && dataAry.length > 0)) {
            this.setState({ defaultMillisecond, maxOpenTablePanel })
            return;
          }
          let key = [];
          let treeSelectData = JSON.parse(JSON.stringify(dataAry[0]));
          treeSelectData.ID = treeSelectData.wTemplateCatID;
          treeSelectData.descripts = treeSelectData.templateDesc;
          treeSelectData.treeType = treeSelectData && treeSelectData.templateTreeType ? treeSelectData.templateTreeType : 'CATALOG';
          if (treeSelectData && 'patEMRRecordID' in treeSelectData && treeSelectData.patEMRRecordID) {
            key.push(treeSelectData.patEMRRecordID);
          } else {
            key.push(treeSelectData.wTemplateCatID);
          }
          let EMRQCFlag = this.props.fGroup ? 'N' : res.result?.EMRQCFlag || 'N';
          this.setState({
            EMRQCFlag, // 病历质控退回
            selectedKeys: key,
            defaultMillisecond,
            maxOpenTablePanel,
            spinLoading: true,
            loadingTitle: '病历模板加载中……'
          }, () => {
            EMRQCFlag === 'Y' && this.getQualityControlFormData();
            let obj = JSON.parse(JSON.stringify(dataAry[0]));
            obj.ID = obj.templateID;
            obj.releaseVersion = obj.eMRReleaseVersion; // 版本号
            if (obj && 'patEMRRecordID' in obj && obj.patEMRRecordID) {
              // obj.ID = obj.patEMRRecordID;
              obj.flag = 'patientRecords';
              obj.treeType = 'TEMPLATE';
              obj.closable = 'N';
              obj.descripts = obj?.templateDesc || '病历';
              this.handleLoadingMedicalRecords(treeSelectData, obj, 'patientRecords');
            } else {
              this.setState({ modalRowData: obj }, () => { // 加载病历模板
                this.getModalTemplateData(treeSelectData, 'default');
              })
            }
          })
        }
      }
    })
  }

  // 处理tree数据
  filterTreeData = (treeData, type, oldItem) => {
    let data = treeData && treeData.map(item => {
      // 当为首程并且首程下存在病程时则首程的progressID就为病程ID;
      let progressID = item && item.subCatalog && item.subCatalog.length > 0 && item.subCatalog[0].treeType && item.subCatalog[0].treeType === 'PROGRESS' ? 'first' : '';
      return {
        title: item.descripts,
        key: item.ID,
        ID: item && item.treeType && item.treeType === 'PROGRESS' ? (oldItem && oldItem.ID ? oldItem.ID : '') : item.ID,
        progressID: item && item.treeType && item.treeType === 'PROGRESS' ? item.ID : progressID,
        treeType: item && item.treeType ? item.treeType : (item && item.subCatalog ? 'CATALOG' : 'TEMPLATE'),
        ...item,
        ...oldItem,
        children: this.filterTreeData(item.subCatalog, type, item && item.treeType && item.treeType === 'TEMPLATE' ? item : {})
      }
    });
    return data;
  }

  // 3.6.1.根据患者获取病历模板分组目录树
  getTreeData = (type) => {
    let { recordData } = this.state;
    let data = {
      params: [{
        admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ''),
        wTempVer: type === 'patientRecords' ? 'Y' : undefined, // 是否查询导航目录模板版本信息
        patEMRRec: type === 'patientRecords' ? 'Y' : undefined, // 是否查询患者已填写病历信息
        locID: type === 'patientRecords' ? (this.props && this.props.locID ? this.props.locID : '') : undefined, // 患者病历预览界面专用 -- 科室ID
        fGroup: type === 'patientRecords' ? (this.props && this.props.fGroup ? this.props.fGroup : '') : undefined, // 患者病历预览界面专用 -- 职能科室
      }]
    }
    $http.post('urlS', this, {
      code: '06050006',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let arr = this.filterTreeData(res.result, type);
          if (type === 'patientRecords') {
            this.setState({ treeData: arr, commitFlag: res.result && res.result.length > 0 ? res.result[0].commitFlag : '', commitBtnDesc: res.result && res.result.length > 0 ? res.result[0].commitBtnDesc : '' }, () => {
              this.generateList(this.state.treeData, 'patientRecords')
            })
          } else {
            this.setState({ treeData: arr }, () => {
              this.generateList(this.state.treeData, 'treeData')
            })
          }
        } else {
          if (type === 'patientRecords') {
            this.setState({ patientRecords: [] })
          } else {
            this.setState({ treeData: [] })
          }
        }
      }
    })
  }

  // 渲染树节点
  renderTreeNodes = data => data && data.map((item) => {
    let inputValue = this.state.templateName;
    const index = item.title && item.title.indexOf(inputValue);
    const beforeStr = item.title && item.title.substr(0, index);
    const afterStr = item.title && item.title.substr(index + inputValue.length);
    const title = index > -1 ? (
      <span>
        {beforeStr}
        <span style={{ color: '#FF7F00' }}>{inputValue}</span>
        {afterStr}
      </span>
    ) : <span>{item.title}</span>;
    // progressID存在并且不等于first则为病程 为first则为首程（病程主节点）
    let type = item.treeType === 'CATALOG' ? 'folder-open' : ((item.treeType === 'TEMPLATE' && !(item.progressID && item.progressID !== 'first')) ? 'folder' : 'file');
    if (item.children) {
      return (
        <TreeNode
          key={item.key}
          dataRef={item}
          icon={<Icon type={type} />}
          title={(
            <Tooltip title={title} placement="right">
              <span
                className='ellipsis'
                style={{ width: '150px', display: 'inline-block' }}
                onClick={() => this.handleAnchorPositioning(item)}
              >
                {title}
              </span>
            </Tooltip>
          )}
        >
          {this.renderTreeNodes(item.children)}
        </TreeNode>
      );
    }
    return (
      <TreeNode
        key={item.key}
        dataRef={item}
        icon={<Icon type={type} />}
        title={(
          <Tooltip title={title} placement="right">
            <span
              className='ellipsis'
              style={{ width: '150px', display: 'inline-block' }}
              onClick={() => this.handleAnchorPositioning(item)}
            >
              {title}
            </span>
          </Tooltip>
        )}
      />
    )
  })

  // 锚点定位
  handleAnchorPositioning = item => {
    let { recordActiveKey } = this.state;
    let recordID = 'record' + item.ID;
    if (item && item.treeType === 'PROGRESS') {
      recordActiveKey && this[recordActiveKey] && this[recordActiveKey].handleAnchorPositioning ?
        this[recordActiveKey].handleAnchorPositioning(recordID) :
        (this.caseTemplateChild && this.caseTemplateChild.handleAnchorPositioning && this.caseTemplateChild.handleAnchorPositioning(recordID));
    }
  }

  getParentKey = (key, tree) => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.children) {
        if (node.children.some(item => item.key === key)) {
          parentKey = node.key;
        } else if (this.getParentKey(key, node.children)) {
          parentKey = this.getParentKey(key, node.children);
        }
      }
    }
    return parentKey;
  };

  dataList = []; // 病历模板
  generateList = (data, type) => {
    for (let i = 0; i < data.length; i++) {
      const node = data[i];
      const key = node.key;
      this.dataList.push({ key, title: node.title });
      if (node.children) {
        this.generateList(node.children, type);
      }
    }

    // 默认进来tree全部加载
    let treeData = this.state.treeData;
    let dataList = this.dataList;
    const expandedKeys = dataList.map((item) => {
      return this.getParentKey(item.key, treeData);
    }).filter((item, i, self) => item && self.indexOf(item) === i);
    this.setState({
      expandedKeys,
    });
  };

  handleTemplateNameChange = e => {
    const templateName = e.target.value;
    let dataList = this.dataList;
    let treeData = JSON.parse(JSON.stringify(this.state.treeData));
    const expandedKeys = dataList.map((item) => {
      if (templateName.length === 0) return null;
      if (item.title && item.title.indexOf(templateName) > -1) {
        return this.getParentKey(item.key, treeData);
      }
      return null;
    }).filter((item, i, self) => item && self.indexOf(item) === i);
    this.setState({
      expandedKeys: expandedKeys && expandedKeys.length > 0 ? expandedKeys : [],
      templateName: e.target.value,
      autoExpandParent: true,
    });
  }

  handleRecordsExpand = (expandedKeys) => {
    // console.log('触发了onExpand', expandedKeys)
    this.setState({
      expandedKeys: expandedKeys,
      autoExpandParent: false,
    });
  }

  // 选择患者病历目录
  handleRecordsSelect = (keys, event) => {
    let { spinLoading } = this.state;
    let selectData = event.node.props.dataRef;
    let treeSelectData = JSON.parse(JSON.stringify(selectData));
    if (!(keys && keys.length > 0)) {
      return;
    }
    if ((selectData && !(selectData.treeType === 'TEMPLATE' || (selectData.treeType === 'CATALOG' && selectData.parentID))) || spinLoading) { // 树类型不为TEMPLATE时不给予选中及其他操作
      return;
    }
    // let selectedKeys = []; // 关联选中病历模板
    // selectedKeys.push(treeSelectData.wTempCataID);
    this.setState({ selectedKeys: keys }, () => {
      treeSelectData.ID = treeSelectData.wTempCataID;
      selectData.BSEMRRDParRef = selectData.patEMRRecordID; // 病程记录ID
      if (this.state.selectedKeys && this.state.selectedKeys.length > 0 && (selectData.treeType === 'TEMPLATE' || selectData.treeType === 'PROGRESS')) {
        this.getPatienHistoryData(treeSelectData, selectData, 'patientRecords')
      } else if (this.state.selectedKeys && this.state.selectedKeys.length > 0 && selectData.treeType === 'CATALOG' && selectData.parentID) {
        this.getModalTemplateData(selectData)
      }
    })
  }

  // 双击患者病历目录树
  handleRecordsDoubleClickTreeNodes = (status, record) => {
    let { spinLoading } = this.state;
    let selectData = record.props != undefined ? record.props.dataRef : record;
    if ((selectData && !(selectData.treeType === 'TEMPLATE' || (selectData.treeType === 'CATALOG' && selectData.parentID))) || spinLoading) { // 树类型不为TEMPLATE时不给予选中及其他操作
      return;
    }
    let treeSelectData = JSON.parse(JSON.stringify(selectData));
    let ID = selectData && selectData.ID ? selectData.ID : '';
    let key = [];
    key.push(ID);
    // let selectedKeys = []; // 关联选中病历模板
    // selectedKeys.push(treeSelectData.wTempCataID);
    this.setState({ selectedKeys: key }, () => {
      treeSelectData.ID = treeSelectData.wTempCataID;
      selectData.BSEMRRDParRef = selectData.patEMRRecordID; // 病程记录ID
      if (selectData && (selectData.treeType === 'TEMPLATE' || selectData.treeType === 'PROGRESS')) {
        this.getPatienHistoryData(treeSelectData, selectData, 'patientRecords');
      } else if (selectData && selectData.treeType === 'CATALOG') {
        this.getModalTemplateData(selectData)
      }
    })
  }

  // 确认引用
  handleOk = (record) => {
    let falg = 'sampleDirectory'
    if (JSON.stringify(record) == '{}') {
      record = this.getDataRelatedToMedicalRecords('treeSelectData');
      let modalRowData = this.getDataRelatedToMedicalRecords('treeSelectData');
      falg = modalRowData?.flag || falg;
    }
    record.isHanle = this.state.isHanle;
    let treeSelectData = JSON.parse(JSON.stringify(record));
    treeSelectData.ID = treeSelectData.wTempCataID;
    this.getPatienHistoryData(treeSelectData, record, falg);
  }

  handleCancel = () => {
    this.setState({ spinLoading: false });
  }

  // 3.6.2.根据分组目录获取模板
  getModalTemplateData = Util.debounce((treeSelectData, isHanle) => {
    let { modalRowData, recordData } = this.state;
    let data = {
      params: [{
        groupTemplateID: treeSelectData.ID, // 分组目录ID - 导航目录ID
        admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ''),
      }]
    }
    $http.post('urlS', this, {
      code: '06050007',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          for (var i = 0; i < res.result.length; i++) {
            if (res.result[i].ID === modalRowData.ID) {
              res.result[i].checked = true;
              modalRowData = res.result[i];
              break;
            }
          }
          let modalTemplateData = res.result.filter(function (item) { return item.releaseVersion });
          this.setState({ modalTemplateData, oldModalTemplateData: modalTemplateData, isHanle: isHanle ? isHanle : '' }, () => {
            if (this.state.isHanle !== 'default') {
              // if (this.state.modalTemplateData && this.state.modalTemplateData.length > 1) {
              // this.showModal();
              this.medicalRecordTemplate && this.medicalRecordTemplate.modifyVisible(true, treeSelectData, this.state.modalTemplateData);
              // } else {
              // 	// 获取患者病历数据
              // 	let obj = this.state.modalTemplateData && this.state.modalTemplateData.length > 0 ? this.state.modalTemplateData[0] : {};
              // 	this.getPatienHistoryData(treeSelectData, obj, 'loadTemplate')
              // }
            } else {
              this.setState({ modalRowData }, () => {
                // closable -- tab是否可以删除
                this.getPatienHistoryData(treeSelectData, { ...modalRowData, isHanle, closable: 'N' }, 'loadTemplate');
              })
            }
          })
        } else {
          this.setState({ modalTemplateData: [], oldModalTemplateData: [], spinLoading: false });
        }
      },
      error: function () {
        this.setState({ modalTemplateData: [], oldModalTemplateData: [], spinLoading: false });
      }
    })
  })

  // 3.6.8.获取患者病历数据
  getPatienHistoryData = Util.debounce((treeSelectData, obj, flag) => {
    // console.log('获取患者病历数据', treeSelectData, obj, flag)
    let oldModalRowData = this.state.modalRowData && this.state.modalRowData.ID ? JSON.parse(JSON.stringify(this.state.modalRowData)) : obj; // 历史选择的模板数据
    let isModify = this.getModified();
    let _this = this;
    if (obj.isHanle !== 'default' && isModify) {
      confirm({
        title: <div>当前病历 <span style={{ fontWeight: '900' }}>{oldModalRowData.descripts}</span> 已修改，是否需要保存？</div>,
        // content: '当前显示的病历模板为：' + oldModalRowData.descripts,
        okText: '是->保存',
        cancelText: '否->无需保存',
        onOk() {
          // obj.load = true; // 是否加载切换的病历模板
          // _this.handleSave(treeSelectData, obj);
          obj.load = true; // 是否加载切换的病历模板
          obj.flag = flag;
          obj.saveType = 'auto';
          _this.setState({ spinLoading: true, loadingTitle: '保存中……' }, () => {
            _this.handleSave(treeSelectData, obj);
          })
        },
        onCancel() {
          _this.handleLoadingMedicalRecords(treeSelectData, obj, flag)
        },
      });

      if (flag === 'cancel') {
        this.handleCancel();
      }
    } else {
      _this.handleLoadingMedicalRecords(treeSelectData, obj, flag)
    }
  })

  // 判断文件内容是否修改
  getModified = () => {
    let { recordActiveKey } = this.state;
    let isModify = recordActiveKey && this[recordActiveKey] && this[recordActiveKey].getModified ?
      this[recordActiveKey].getModified() :
      (this.caseTemplateChild && this.caseTemplateChild.getModified ? this.caseTemplateChild.getModified() : false);
    return isModify
  }

  // 病历加载
  handleLoadingMedicalRecords = (treeSelectData, obj, flag) => {
    this.handleAddTab(obj, () => {
      this.setState({ spinLoading: true, loadingTitle: '病历加载中……', templateID: obj.templateID }, () => {
        if (flag === 'patientRecords') {
          // let eMRRecordID = obj && obj.BSEMRRDParRef ? obj.BSEMRRDParRef : obj.patEMRRecordID; // 病程记录ID
          // if (obj && obj.addLockFlag === 'N') { // 判断病历加载是否需要加锁操作
          let modifyParams = [{
            keys: 'isDeleteRecord',
            values: true
          }]
          let newPanes = this.modifyDataRelatedToMedicalRecords(modifyParams);
          this.setState({ panes: newPanes }, () => { // 加载已保存的患者病历模板可以删除
            this.newLoadingMedicalRecords(treeSelectData, obj, flag);
          })
          // } else {
          // 	this.updateMedicalRecordLockStatus(eMRRecordID, treeSelectData, obj, flag);
          // }
        } else {
          this.SaveMedicalRecord(treeSelectData, obj, flag)
        }
        this.getPatientDeletedHistory(treeSelectData);
      })
    });
  }

  // 加载病历模板
  handleLoadingMedicalRecordTemplate = (treeSelectData, obj, flag) => {
    try {
      let { recordData, titleData, defaultMillisecond, recordActiveKey } = this.state;
      let newPanes = JSON.parse(JSON.stringify(this.state.panes));
      // let oldEMRRecordID = eMRRecordID;
      let data = {
        params: [{
          patEMRRecordID: obj && obj.BSEMRRDParRef ? obj.BSEMRRDParRef : obj.patEMRRecordID,
          admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ''),
          groupTemplateID: obj.ID, // 分组模板ID
          power: this.props.medicalType == 'Z' ? 'OutHospRecord' : ''
        }]
      }
      $http.post('urlS', this, {
        code: '06050016',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            // console.log(res.result) // eMRRecordID 
            let authority = res.result && res.result.authority ? res.result.authority : {};
            let isOperable = this.props.isOperable ? this.props.isOperable : ((obj && (obj.BSEMRRDParRef || obj.patEMRRecordID) && authority && (authority.addOrNot === 'Y' || authority.updateOrNot === 'Y')) ? 'N' : 'Y'); // 是否可操作
            // let isOperable = this.props.isOperable ? this.props.isOperable : (obj && obj.eMRRecordIsAvailable ? (obj.eMRRecordIsAvailable === 'Y' ? 'N' : 'Y') : 'N'); // 是否可操作
            obj.flag = flag; // 保存调用类型
            obj.removeLockFlag = authority.removeLockFlag;
            let templatePath = res.result && res.result.templatePath ? res.result.templatePath : '';
            let eMRRecordID = obj && obj.BSEMRRDParRef ? obj.BSEMRRDParRef : obj.patEMRRecordID;
            let progressID = obj && obj.progressID ? obj.progressID : ''; // 病程记录ID
            let templateParams = [templatePath, res.result.dataSource, isOperable, 'boolFalse', titleData && titleData.patSexDesc ? titleData.patSexDesc : '', { ...obj, releaseVersion: obj.releaseVersion }, obj.templateID, progressID];
            for (var j = 0; j < newPanes.length; j++) {
              if (newPanes[j].key === recordActiveKey) {
                newPanes[j].treeSelectData = treeSelectData;
                newPanes[j].modalRowData = obj;
                newPanes[j].templatePath = templatePath;
                newPanes[j].isUnlocking = true;
                newPanes[j].eMRRecordID = eMRRecordID;
                newPanes[j].templateParams = templateParams;
              }
            }
            this.setState({
              templatePath, eMRRecordID, treeSelectData, panes: newPanes, templateParams, modalRowData: obj, spinLoading: false, isUnlocking: true
            }, () => {
              this.state.templatePath ?
                (recordActiveKey && this[recordActiveKey] && this[recordActiveKey].setElementTextByID ?
                  this[recordActiveKey].setElementTextByID(...templateParams) :
                  this.caseTemplateChild.setElementTextByID(...templateParams)) :
                this.caseTemplateChild?.NewFile();
              if (flag === 'cancel') {
                this.handleCancel();
              }
              // console.log('oldModalRowData', oldModalRowData, obj)
              // if (obj && obj.isHanle !== 'default' && oldModalRowData && oldModalRowData.removeLockFlag === 'Y') {
              // 	this.updateMedicalRecordLockStatus(oldModalRowData && oldModalRowData.BSEMRRDParRef ? oldModalRowData.BSEMRRDParRef : oldEMRRecordID); // 解锁
              // }
              authority && authority.noChangeTip ? message.info(authority.noChangeTip) : '';
              if (isOperable === 'N' && this.props && this.props.caseInformationPageTabs !== 'N') { // 定时保存病历
                if (timer) {
                  clearInterval(timer);
                  timer = null;
                }
                timer = setInterval(() => {
                  // this.savePatientMedicalRecord('handleLoadingMedicalRecordTemplate');
                  console.log('触发了保存');
                }, defaultMillisecond ? (defaultMillisecond * 1000) : (60 * 1000)) // 默认一分钟保存一次
              }
            })
          } else {
            this.setState({ spinLoading: false })
          }
        },
        error: function () {
          this.setState({ spinLoading: false })
        }
      })
    } catch (error) {
      console.log(error);
    }
  }

  // 加载病历 - 加载已保存的患者病历模板可以删除
  newLoadingMedicalRecords = async (treeSelectData, obj, flag) => {
    try {
      // let selectedKeys = []; // 患者病历选中操作
      // selectedKeys.push(obj.ID);
      let expandedKeys = []; // 初始化时默认展开默认加载的模板目录树
      expandedKeys.push(obj && obj.wTempCataID ? obj.wTempCataID : obj.wTemplateCatID);
      let { recordData, titleData, defaultMillisecond, recordActiveKey } = this.state;
      let newPanes = JSON.parse(JSON.stringify(this.state.panes));
      let data = {
        params: [{
          patEMRRecordID: obj && obj.BSEMRRDParRef ? obj.BSEMRRDParRef : obj.patEMRRecordID,
          admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ''),
          // catalogueID: treeSelectData.ID, // 分组目录ID
          // groupTemplateID: obj.ID, // 分组模板ID
          power: this.props.medicalType == 'Z' ? 'OutHospRecord' : ''
        }]
      }
      let res = await React.$asyncPost(this, '06050008', data);
      let authority = res.result && res.result.authority ? res.result.authority : {};
      let isOperable = this.props.isOperable ? this.props.isOperable : ((obj && (obj.BSEMRRDParRef || obj.patEMRRecordID) && authority && (authority.addOrNot === 'Y' || authority.updateOrNot === 'Y')) ? 'N' : 'Y'); // 是否可操作
      // let isOperable = this.props.isOperable ? this.props.isOperable : (obj && obj.eMRRecordIsAvailable ? (obj.eMRRecordIsAvailable === 'Y' ? 'N' : 'Y') : 'N'); // 是否可操作
      obj.flag = flag; // 保存调用类型
      obj.removeLockFlag = authority.removeLockFlag;
      let templatePath = res.result && res.result.templatePath ? res.result.templatePath : '';
      let isUnlocking = this.props.isOperable === 'Y' ? true : false;
      let recordDataID = res.result && res.result.recordDataID ? res.result.recordDataID : '';
      let eMRRecordID = res.result && res.result.eMRRecordID ? res.result.eMRRecordID : '';
      let needUpdateData = res.result && res.result.needUpdateData && res.result.needUpdateData.length ? res.result.needUpdateData : [];
      let progressID = obj && obj.progressID ? obj.progressID : ''; // 病程记录ID
      let existFieldValIDData = res.result && res.result.existFieldValIDData ? res.result.existFieldValIDData : []; // 回带弹窗选择的基本数据
      let templateParams = [
        templatePath, res.result.dataSource, isOperable, 'boolFalse',
        titleData && titleData.patSexDesc ? titleData.patSexDesc : '', { ...obj, releaseVersion: obj.releaseVersion }, obj.templateID, progressID, needUpdateData,
        existFieldValIDData, res.result.RYJLCorrectionFieldID
      ];
      if (flag === 'templateParams') {
        return templateParams;
      }
      for (var i = 0; i < needUpdateData.length; i++) {
        needUpdateData[i].key = i + 1;
      }
      for (var j = 0; j < newPanes.length; j++) {
        if (newPanes[j].key === recordActiveKey) {
          newPanes[j].treeSelectData = treeSelectData;
          newPanes[j].modalRowData = obj;
          newPanes[j].templatePath = templatePath;
          newPanes[j].isUnlocking = isUnlocking;
          newPanes[j].recordDataID = recordDataID;
          newPanes[j].eMRRecordID = eMRRecordID;
          newPanes[j].templateParams = templateParams;
        }
      }
      this.setState({ // recordDataID -- 病历记录数据ID
        templatePath, eMRRecordID, treeSelectData, modalRowData: obj, spinLoading: false, isUnlocking, recordDataID, panes: newPanes, templateParams
      }, () => {
        this.state.templatePath ? (recordActiveKey && this[recordActiveKey] && this[recordActiveKey].setElementTextByID ?
          this[recordActiveKey].setElementTextByID(
            ...templateParams
          ) :
          this.caseTemplateChild?.setElementTextByID(
            ...templateParams
          )
        ) :
          this.caseTemplateChild?.NewFile();
        if (flag === 'cancel') {
          this.handleCancel();
        }
        // console.log('oldModalRowData', oldModalRowData, obj)
        // if (obj && obj.isHanle !== 'default' && oldModalRowData && oldModalRowData.removeLockFlag === 'Y') {
        // 	this.updateMedicalRecordLockStatus(oldModalRowData && oldModalRowData.BSEMRRDParRef ? oldModalRowData.BSEMRRDParRef : oldEMRRecordID); // 解锁
        // }
        authority && authority.noChangeTip ? message.info(authority.noChangeTip) : '';
        if (isOperable === 'N' && this.props && this.props.caseInformationPageTabs !== 'N') { // 定时保存病历
          if (timer) {
            clearInterval(timer);
            timer = null;
          }
          timer = setInterval(() => {
            // this.savePatientMedicalRecord('newLoadingMedicalRecords');
            console.log('触发了保存');
          }, defaultMillisecond ? (defaultMillisecond * 1000) : (60 * 1000)) // 默认一分钟保存一次
        }
      })
    } catch (error) {
      console.log(error)
      this.setState({ patienHistoryData: [], spinLoading: false })
    }
  }

  // 3.6.3.保存病历记录
  SaveMedicalRecord = Util.debounce((treeSelectData, obj, flag, selectionXml) => {
    let { recordData, recordActiveKey } = this.state;
    let data = {
      params: [{
        admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ''),
        cataLogID: treeSelectData.ID, // 分组模板目录ID
        seqNo: '',
        templateID: obj.ID, // 病历模板ID
        sPatRecPower: flag === 'courseOfDisease' ? 'saveEMRProgress' : undefined
      }]
    }
    $http.post('urlS', this, {
      code: '06050001',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let recordID = res && res.ID ? res.ID : '';
          obj.BSEMRRDParRef = recordID;
          let modifyParams = [{
            keys: 'isDeleteRecord',
            values: false
          }]
          let newPanes = this.modifyDataRelatedToMedicalRecords(modifyParams);
          if (flag === 'courseOfDisease') { // 插入病程
            recordActiveKey && this[recordActiveKey] && this[recordActiveKey].insertTheCourseOfDisease ?
              this[recordActiveKey].insertTheCourseOfDisease(selectionXml, recordID, obj) :
              (this.caseTemplateChild && this.caseTemplateChild.insertTheCourseOfDisease && this.caseTemplateChild.insertTheCourseOfDisease(selectionXml, recordID, obj))
          } else if (flag === 'sampleDirectory') { // 加载范例病历
            this.setState({ panes: newPanes }, () => {
              this.handleLoadSampleMedicalRecord(treeSelectData, obj, flag);
            })
          } else if (flag === 'loadTemplate' || flag === 'cancel') { // 加载病历模板
            this.setState({ panes: newPanes }, () => { // 加载的病历模板不能删除
              this.handleLoadingMedicalRecordTemplate(treeSelectData, obj, flag);
            })
          } else {
            modifyParams[0].values = true;
            this.setState({ panes: newPanes }, () => { // 加载已保存的患者病历模板可以删除
              this.newLoadingMedicalRecords(treeSelectData, obj, flag);
            })
          }
        } else {
          recordActiveKey && this[recordActiveKey] && this[recordActiveKey].clearCourseOfDiseaseLoading ?
            this[recordActiveKey].clearCourseOfDiseaseLoading() :
            (this.caseTemplateChild && this.caseTemplateChild.clearCourseOfDiseaseLoading && this.caseTemplateChild.clearCourseOfDiseaseLoading());
          this.setState({ spinLoading: false });
        }
      },
      error: function () {
        recordActiveKey && this[recordActiveKey] && this[recordActiveKey].clearCourseOfDiseaseLoading ?
          this[recordActiveKey].clearCourseOfDiseaseLoading() :
          (this.caseTemplateChild && this.caseTemplateChild.clearCourseOfDiseaseLoading && this.caseTemplateChild.clearCourseOfDiseaseLoading());
        this.setState({ spinLoading: false });
      }
    })
  })

  // 加载范例病例
  handleLoadSampleMedicalRecord = async (treeSelectData, obj, flag) => {
    try {
      let { recordData, titleData, recordActiveKey } = this.state;
      let newPanes = JSON.parse(JSON.stringify(this.state.panes));
      let data = {
        params: [{
          // obj && obj.BSEMRRDParRef ? obj.BSEMRRDParRef : obj.patEMRRecordID
          patEMRRecordID: '',
          admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ''),
          groupTemplateID: obj.ID, // 分组模板ID
          power: this.props.medicalType == 'Z' ? 'OutHospRecord' : '',
          examTempID: treeSelectData?.examTempID || ''
        }]
      }
      let res = await React.$asyncPost(this, '06050106', data);
      let authority = res.result && res.result.authority ? res.result.authority : {};
      let isOperable = this.props.isOperable ? this.props.isOperable : ((obj && (obj.BSEMRRDParRef || obj.patEMRRecordID) && authority && (authority.addOrNot === 'Y' || authority.updateOrNot === 'Y')) ? 'N' : 'Y'); // 是否可操作
      // let isOperable = this.props.isOperable ? this.props.isOperable : (obj && obj.eMRRecordIsAvailable ? (obj.eMRRecordIsAvailable === 'Y' ? 'N' : 'Y') : 'N'); // 是否可操作
      obj.flag = flag; // 保存调用类型
      obj.removeLockFlag = authority.removeLockFlag;
      let templatePath = res.result && res.result.templatePath ? res.result.templatePath : '';
      let eMRRecordID = obj && obj.BSEMRRDParRef ? obj.BSEMRRDParRef : obj.patEMRRecordID;
      let progressID = obj && obj.progressID ? obj.progressID : ''; // 病程记录ID
      let templateParams = [templatePath, res.result.dataSource, isOperable, 'boolFalse', titleData && titleData.patSexDesc ? titleData.patSexDesc : '', { ...obj, releaseVersion: obj.releaseVersion }, obj.templateID, progressID];
      for (var j = 0; j < newPanes.length; j++) {
        if (newPanes[j].key === recordActiveKey) {
          newPanes[j].treeSelectData = treeSelectData;
          newPanes[j].modalRowData = obj;
          newPanes[j].templatePath = templatePath;
          newPanes[j].isUnlocking = true;
          newPanes[j].eMRRecordID = eMRRecordID;
          newPanes[j].templateParams = templateParams;
        }
      }
      this.setState({
        templatePath, eMRRecordID, treeSelectData, panes: newPanes, templateParams,
        modalRowData: obj, spinLoading: false, isUnlocking: true
      }, () => {
        this.state.templatePath ?
          (recordActiveKey && this[recordActiveKey] && this[recordActiveKey].setElementTextByID ?
            this[recordActiveKey].setElementTextByID(...templateParams) :
            this.caseTemplateChild?.setElementTextByID(...templateParams)) :
          this.caseTemplateChild?.NewFile();
        this.medicalRecordTemplate && this.medicalRecordTemplate.modifyVisible(false);
        authority && authority.noChangeTip ? message.info(authority.noChangeTip) : '';
      })
    } catch (error) {
      console.log(error);
      this.setState({ spinLoading: false });
    }
  }

  // 保存插入的病程记录
  handleSaveTheInsertedCourse = (selectionXml, templateID, templateData = {}) => {
    let treeSelectData = this.getDataRelatedToMedicalRecords('treeSelectData');
    let obj = { ...templateData };
    obj.ID = templateID;
    this.SaveMedicalRecord(treeSelectData, obj, 'courseOfDisease', selectionXml);
  }

  // 3.6.5.保存患者病历数据
  savePatientMedicalRecord = (newWTreeSelectData, record, fn) => {
    let { recordActiveKey } = this.state;
    let modalRowData = this.getDataRelatedToMedicalRecords('modalRowData');
    let oldTreeSelectData = this.getDataRelatedToMedicalRecords('treeSelectData');
    let templateData = recordActiveKey && this[recordActiveKey] && this[recordActiveKey].getTemplateXml ?
      this[recordActiveKey].getTemplateXml('form') :
      (this.caseTemplateChild && this.caseTemplateChild.getTemplateXml ? this.caseTemplateChild.getTemplateXml('form') : '');
    // console.log(templateData)
    // if (!(templateData && templateData.status)) {
    //   this.setState({ spinLoading: false });
    //   return;
    // }
    let data = {
      params: [{
        BSEMRRDParRef: modalRowData && modalRowData.BSEMRRDParRef ? modalRowData.BSEMRRDParRef : modalRowData.patEMRRecordID, // 病历记录ID
        recordData: templateData && templateData.xmlStr ? templateData.xmlStr : '', // 病历记录数据 --- 模板xml
        progressRecIDAry: templateData && templateData.allRecordID ? templateData.allRecordID : [], // 病历记录数据 --- 病程记录ID
        progressRecDataSource: templateData?.recordDataSource || [],
        submitOrNot: 'N', // submitOrNot
        auditOrNot: 'N', // 是否审核标志
        lockStatus: 'Y', // 锁定标志
        archivingStatus: 'U', // 归档标志
        wCatalogueID: oldTreeSelectData.ID, // 分组目录ID
        versionID: modalRowData && modalRowData.releaseVersion ? modalRowData.releaseVersion : '', // 病历模板ID
        patRecDataSource: recordActiveKey && this[recordActiveKey] && this[recordActiveKey].getMedicalRecordFileIDAndValue ?
          this[recordActiveKey].getMedicalRecordFileIDAndValue() :
          (this.caseTemplateChild && this.caseTemplateChild.getMedicalRecordFileIDAndValue && this.caseTemplateChild.getMedicalRecordFileIDAndValue()), // 病历所有的输入域以及对应的值
      }]
    }
    // console.log('data', data)
    $http.post('urlS', this, {
      code: '06050004',
      data: data,
      success: async function (res) {
        if (+res.errorCode === 0) {
          let recordDataID = res.result && res.result.recordDataID ? res.result.recordDataID : ''; // recordDataID -- 病历记录数据ID
          let templateParams = await this.newLoadingMedicalRecords(oldTreeSelectData, modalRowData, 'templateParams');
          let modifyParams = [{
            keys: 'recordDataID',
            values: recordDataID
          }, {
            keys: 'isDeleteRecord',
            values: true
          }, {
            keys: 'templateParams',
            values: templateParams
          }];
          let newPanes = this.modifyDataRelatedToMedicalRecords(modifyParams);
          this.setState({ isHanle: '', spinLoading: false, recordDataID, panes: newPanes });
          this.getTreeData('patientRecords'); // 保存成功之后重新加载患者病历
          recordActiveKey && this[recordActiveKey] && this[recordActiveKey].resetModified ?
            this[recordActiveKey].resetModified('isModifyPermissions') :
            (this.caseTemplateChild && this.caseTemplateChild.resetModified ? this.caseTemplateChild.resetModified('isModifyPermissions') : ''); // 保存成功后修改编辑状态
          // handleLoadingMedicalRecordTemplate -- 病历模板   newLoadingMedicalRecords -- 已写过的病历
          if (newWTreeSelectData === 'handleLoadingMedicalRecordTemplate' || newWTreeSelectData === 'newLoadingMedicalRecords' || newWTreeSelectData === 'handleLoadSampleMedicalRecord' || newWTreeSelectData === 'saveBeforePrinting') { // 自动保存
            if (newWTreeSelectData === 'saveBeforePrinting' && fn) { // 如果为打印前保存的则保存完成后唤起打印
              fn();
              return;
            }
            return;
          }; // BSEMRRDParRef
          let key = [];
          key.push(modalRowData && modalRowData.BSEMRRDParRef ? modalRowData.BSEMRRDParRef : modalRowData.patEMRRecordID);
          // this.setState({ selectedKeys: key }, () => {
          message.success('保存成功', this.state.userData && this.state.userData.messageTime ? this.state.userData.messageTime : 3);
          if (newWTreeSelectData && newWTreeSelectData.ID) { // 判断是否自动保存的，
            this.setState({ treeSelectData: oldTreeSelectData });
          } else {
            this.setState({ selectedKeys: key })
          }
          if (record && record.load) { // 判断是否保存后需要加载新操作的模板，需要的话传入新模板数据
            this.handleLoadingMedicalRecords(newWTreeSelectData, record, record.flag);
          }
          if (fn) {
            fn();
          }
        } else {
          this.setState({ spinLoading: false });
          recordActiveKey && this[recordActiveKey] && this[recordActiveKey].resetModified ?
            this[recordActiveKey].resetModified('clearSaveBtnLoading') :
            (this.caseTemplateChild && this.caseTemplateChild.resetModified ? this.caseTemplateChild.resetModified('clearSaveBtnLoading') : '');
        }
      },
      error: function () {
        this.setState({ spinLoading: false });
        recordActiveKey && this[recordActiveKey] && this[recordActiveKey].resetModified ?
          this[recordActiveKey].resetModified('clearSaveBtnLoading') :
          (this.caseTemplateChild && this.caseTemplateChild.resetModified ? this.caseTemplateChild.resetModified('clearSaveBtnLoading') : '');
      }
    })
  }

  // 保存
  handleSave = (treeSelectData, record, fn) => {
    if (record && record.saveType === 'auto') { // 自动保存不需要加载loading提示
      this.savePatientMedicalRecord(treeSelectData, record, fn);
    } else if (record && record.saveType === 'print') { // 打印前如果有修改先保存
      this.setState({ spinLoading: true, loadingTitle: '加载中' }, () => {
        this.savePatientMedicalRecord(treeSelectData, record, fn);
      })
    } else {
      this.setState({ spinLoading: true, loadingTitle: '保存中' }, () => {
        // this.SaveMedicalRecord(treeSelectData, record, fn);
        this.savePatientMedicalRecord(treeSelectData, record, fn);
      })
    }
  }

  //撤销已删除的记录
  undoDeleted = () => {
    let hasRecordSelect = true;
    let isReturn = false;
    let patientRecords = this.state.treeData[0].children
    let treeSelectData = {}//.wTempCataID
    let { panes } = this.state;
    let currenTabInfo = {}
    panes.map(item => {
      if (item.key == this.state.recordActiveKey)
        currenTabInfo = item
    })
    patientRecords.forEach(data => {
      if (data.ID == currenTabInfo.wTempCataID) {
        treeSelectData.wTempCataID = data.ID
        if (data.treeType == 'CATALOG' && currenTabInfo.ID == currenTabInfo.templateID && data.children.length > 0) {
          isReturn = true;
          Modal.info({
            title: '撤销提示',
            content: (
              <div>
                <p>请选择病历记录！</p>
              </div>
            ),
            onOk() {
              return;
            },
          });
        }
        else if (data.treeType == 'CATALOG' && currenTabInfo.ID == currenTabInfo.templateID && data.children.length == 0) {
          hasRecordSelect = false;
        }
      }
    });
    if (isReturn) return;
    let data = {
      params: [{
        'admID': this.props && this.props.historyAdmID ? this.props.historyAdmID : (this.state.recordData && this.state.recordData.admID ? this.state.recordData.admID : ''), // 就诊记录主键
        'templateDr': currenTabInfo.templateID
      }]
    }
    $http.post('urlS', this, {
      code: '06010111',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.getPatientDeletedHistory(treeSelectData)
          if (hasRecordSelect) {
            this.setState({ contextMenuData: this.state.treeSelectData }, () => { this.deletePatientHistory() })
          }
          else
            this.getTreeData('patientRecords');
        }
      }

    })
  }

  // 查看历史病历时将右侧宽度调宽
  compileVNum = (status) => {
    this.containerWidth = document.getElementById('v_resize_container').offsetWidth
    if (status === 'default') {
      this.setState({
        vNum: 1000,
        vNumLimit: this.containerWidth - 1000,
        showValidateResult: 'show'
      })
    } else {
      this.setState({
        vNum: this.containerWidth / 2 + 50,
        vNumLimit: this.containerWidth / 2 - 50,
        showValidateResult: 'hidden'
      })
    }
  }

  /**
   * 初始化resize信息
   */
  initResizeInfo = () => {
    const hEle = document.getElementById('h_resize_container')
    this.resizeOffsetInfo = this.getEleOffset(hEle)
    this.leftHeight = hEle.offsetHeight
    this.containerWidth = document.getElementById('v_resize_container').offsetWidth

    if (hEle.offsetHeight - this.state.hNum < this.state.hNumLimit) {
      this.setState({
        hNum: hEle.offsetHeight - this.state.hNumLimit
      })
    }
    if (this.containerWidth - this.state.vNum < this.state.vNumLimit) {
      this.setState({
        vNum: this.containerWidth - this.state.vNumLimit,
      })
    }
  }

  /**
   * 获取元素的偏移信息
   */
  getEleOffset(ele) {
    var clientTop = ele.offsetTop
    var clientLeft = ele.offsetLeft
    let current = ele.offsetParent
    while (current !== null) {
      clientTop += current.offsetTop
      clientLeft += current.offsetLeft
      current = current.offsetParent
    }
    return {
      clientTop,
      clientLeft,
      height: ele.offsetHeight,
      width: ele.offsetWidth
    }
  }

  /**
   * 只要鼠标松开或者离开区域，那么就停止resize
    */
  stopResize = () => {
    this.setState({
      isVResize: false
    })
  }

  /**
   * 拖动垂直调整块
   */
  vResizeOver = (e) => {
    const { isVResize, vNum, vNumLimit } = this.state
    if (isVResize && vNum >= vNumLimit && (this.containerWidth - vNum >= vNumLimit)) {
      let newValue = e.clientX - this.resizeOffsetInfo.clientLeft
      if (newValue < vNumLimit) {
        newValue = vNumLimit
      }
      if (newValue > this.containerWidth - vNumLimit) {
        newValue = this.containerWidth - vNumLimit
      }
      this.setState({
        vNum: newValue
      })
    }
  }

  /**
   * 开始拖动垂直调整块
   */
  vResizeDown = () => {
    this.setState({
      isVResize: true
    })
  }

  /**
   * 拖动水平调整块
   */
  hResizeOver = (e) => {
    const { hNum, hNumLimit } = this.state;
    if (hNum >= hNumLimit && (this.resizeOffsetInfo.height - hNum >= hNumLimit)) {
      let newValue = this.resizeOffsetInfo.clientTop + this.resizeOffsetInfo.height - e.clientY
      if (newValue < hNumLimit) {
        newValue = hNumLimit
      }
      if (newValue > this.resizeOffsetInfo.height - hNumLimit) {
        newValue = this.resizeOffsetInfo.height - hNumLimit
      }
      this.setState({
        hNum: newValue
      })
    }
  }

  // 引用
  handleQuote = (str, quoteArr) => {
    let { recordActiveKey } = this.state;
    recordActiveKey && this[recordActiveKey] && this[recordActiveKey].Spechars ?
      this[recordActiveKey].Spechars(str, quoteArr) :
      (this.caseTemplateChild && this.caseTemplateChild.Spechars && this.caseTemplateChild.Spechars(str, quoteArr));
  }

  // 插入知识库xml
  setKnowledgeBaseXMl = (nodeContent, rowData, fn) => {
    let { recordActiveKey } = this.state;
    // console.log(nodeContent, rowData)
    recordActiveKey && this[recordActiveKey] && this[recordActiveKey].InsertXmlString ?
      this[recordActiveKey].InsertXmlString(nodeContent, rowData, fn) :
      (this.caseTemplateChild && this.caseTemplateChild.InsertXmlString && this.caseTemplateChild.InsertXmlString(nodeContent, rowData, fn));
  }

  // 新知识库赋值
  knowledgeBaseAssignment = (filedID, value) => {
    let { recordActiveKey } = this.state;
    recordActiveKey && this[recordActiveKey] && this[recordActiveKey].knowledgeBaseAssignment ?
      this[recordActiveKey].knowledgeBaseAssignment(filedID, value) :
      (this.caseTemplateChild && this.caseTemplateChild.knowledgeBaseAssignment && this.caseTemplateChild.knowledgeBaseAssignment(filedID, value));
  }

  handleCaseInformationRef = ref => {
    this.caseInformationChild = ref;
  }

  // 供病历公共组件调用获取知识库数据
  getChildKnowledgeBaseTreeData = (filedId) => {
    let modalRowData = this.getDataRelatedToMedicalRecords('modalRowData');
    if (this.state.courseID !== filedId) {// 点击同一个病程则不再调用查询知识库方法
      this.setState({ courseID: filedId }, () => {
        this.caseInformationChild.getKnowledgeBaseTreeData(this.state.courseID, modalRowData);
      })
    }
  }

  //提交患者病历
  commitPatEMR = (type) => {
    let { contextMenuData, recordData } = this.state;
    var recordID = contextMenuData.patEMRRecordID;
    if (type == 'ALL') {
      recordID = '';
    }
    let data = {
      params: [{
        recordID: recordID,
        statusCode: 'F',
        type: type,
        admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ''),
      }]
    }
    $http.post('urlS', this, {
      code: '06050022',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          message.success('病历提交成功');
          this.getTreeData('patientRecords'); // 保存成功之后重新加载患者病历  
          var openFlag = false;
          this.state.panes.map((item) => {
            if (item.eMRRecordID == recordID) {
              openFlag = true;
            }
          })
          //如果病历已打开需要刷新页面
          if ((type != 'ALL') && openFlag) {
            this.handleRecordsDoubleClickTreeNodes('', contextMenuData);
          }
        }
      }
    })
  }

  // 删除患者病历
  deletePatientHistory = (type, courseID) => { // type = removeCourse courseID -- 病程ID 删除病程
    let { contextMenuData, recordActiveKey, panes } = this.state;
    console.log(contextMenuData)
    let recordDataID = this.getDataRelatedToMedicalRecords('recordDataID', contextMenuData.key);
    let allRecordID = recordActiveKey && this[recordActiveKey] && this[recordActiveKey].getTemplateXml ?
      this[recordActiveKey].getTemplateXml() :
      (this.caseTemplateChild && this.caseTemplateChild.getTemplateXml && this.caseTemplateChild.getTemplateXml('allRecordID'));
    if (!(contextMenuData && contextMenuData.patEMRRecordID)) {
      message.info('暂不支持删除', this.state.userData && this.state.userData.messageTime);
      return;
    }
    let data = {
      params: [{
        eMRRecordID: type === 'removeCourse' ? courseID : contextMenuData && contextMenuData.patEMRRecordID, // 病历记录主键
        recordDataID: type === 'removeCourse' ? undefined : recordDataID, // 病历记录数据ID
        progressRecIDAry: type === 'removeCourse' ? undefined : (allRecordID && allRecordID.length > 0 ? allRecordID : []), // 病程记录ID
      }]
    }
    $http.post('urlS', this, {
      code: '06010097',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          message.success(res.errorMessage, this.state.userData && this.state.userData.messageTime);
          this.getTreeData('patientRecords'); // 保存成功之后重新加载患者病历
          let targetKey = contextMenuData && contextMenuData.ID && contextMenuData.treeType ? (contextMenuData.treeType + contextMenuData.ID) : (contextMenuData && contextMenuData.ID ? contextMenuData.ID : '');
          let isExist = false; // 刪除左侧已写过的病历判断是否已经打开，已经打开则关闭
          for (var i = 0; i < panes.length; i++) {
            if (panes[i].key === targetKey) {
              isExist = true;
              break;
            }
          }
          if (isExist) {
            this.handleRemoveRecordATab(targetKey);
          }
          if (type !== 'removeCourse') {
            this.setState({ contextMenuData: {} }); // 置空可删除ID
            contextMenuData && this[contextMenuData.key] && this[contextMenuData.key].resetModified ?
              this[contextMenuData.key].resetModified('noSave') :
              (this.caseTemplateChild && this.caseTemplateChild.resetModified ? this.caseTemplateChild.resetModified('noSave') : ''); // 保存成功后修改编辑状态
            if (timer) { // 清除定时保存的定时器
              clearInterval(timer);
              timer = null;
            }
          }
        }
      }
    })
  }

  // 另存为知识库
  handleExampleknow = () => {
    this.setState({
      exampleVisible: true,
      prModal: '另存为知识库'
    }, () => {

    });
  }

  // 患者病历删除状态
  getPatientDeletedHistory = (treeSelectData) => {
    let { recordData, templateTree } = this.state;
    //变量的名称不一致
    let CatID = treeSelectData.wTempCataID ? treeSelectData.wTempCataID : (treeSelectData.wTemplateCatID ? treeSelectData.wTemplateCatID : '');
    let data = {
      params: [{
        'admID': this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ''), //就诊ID
        'catalogueID': CatID, //病历浏览子目录ID
        'EMRIsAvailable': 'N',  //是否显示有效病历
        'eMRtemplateDesc': templateTree,  //描述
      }]
    }
    $http.post('urlS', this, {
      code: '06010096',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let patientHistoryData = res.result && res.result.dataAry ? res.result.dataAry : [];
          let isHasDeletedRecord = false;
          patientHistoryData.map(item => {
            if (item.eMRTemplateID == this.state.templateID)
              isHasDeletedRecord = true;
          })
          this.setState({ isHasDeletedRecord })
        } else {
          this.setState({ isHasDeletedRecord: false })
        }
      }
    })
  }

  //跳转到西药及其他
  goDoctorAdviceStepPage = () => {
    var params = {
      params: [{
        locID: this.state.userData.locID,
        hospID: this.state.userData.hospID,
        groupID: this.state.userData.groupID
      }]
    }
    $http.post('urlDeault', this, {
      code: '03050093',
      data: params,
      success: function (res) {
        if (res.errorCode == '0') {
          for (var i = 0; i < res.result.length; i++) {
            if (res.result[i].code === 'CaseInformationPageHospital') {
              var { upDataComponentSource } = this.props;
              upDataComponentSource && upDataComponentSource(res.result[i]);
              return;
            }
          }
        }
      }
    });
  }

  // 双击患者病历节点加载相应病历模板
  handleStepDoubleClick = (item) => {
    let treeSelectData = JSON.parse(JSON.stringify(item));
    let key = [];
    treeSelectData.ID = treeSelectData.wTemplateCatID;
    let modalRowData = JSON.parse(JSON.stringify(item));
    modalRowData.ID = modalRowData.eMRTemplateID;
    modalRowData.releaseVersion = modalRowData.eMRReleaseVersion;
    key.push(treeSelectData.wTemplateCatID);
    this.setState({ selectedKeys: key }, () => {
      this.getPatienHistoryData(treeSelectData, modalRowData);
    });
  }

  // 另存为范例模板
  handleExampleTemplate = (record = {}) => {
    let templateParams = this.getDataRelatedToMedicalRecords('templateParams') ? this.getDataRelatedToMedicalRecords('templateParams') : this.state.templateParams;
    let treeSelectData = this.getDataRelatedToMedicalRecords('treeSelectData') ? this.getDataRelatedToMedicalRecords('treeSelectData') : this.state.treeSelectData;
    treeSelectData = { ...treeSelectData, ...record };
    let defaultSelectedKeys = record && 'examListID' in record ? (record.examListID + '-' + record.examTempID) : '';
    if (defaultSelectedKeys) {
      treeSelectData.templateDesc = record?.examTempDesc || treeSelectData.templateDesc;
      treeSelectData.templateID = record?.examTemplateID || treeSelectData.templateID;
    }
    treeSelectData.wTempCataID = record?.examTempCataLogID || treeSelectData.wTempCataID || treeSelectData.ID;
    this.sampleTemplate && this.sampleTemplate.modifyVisible(true, templateParams, treeSelectData, defaultSelectedKeys);
  }

  showModule = () => {
    this.setState({
      hideTabs: false
    })
  }

  hideModule = () => {
    this.setState({
      hideTabs: true
    })
  }

  // 更新患者病历记录锁状态
  updateMedicalRecordLockStatus = Util.debounce((eMRRecordID, treeSelectData, obj, flag) => {
    let userData = React.$getSessionData();
    if (!(eMRRecordID && userData && userData.userID)) {
      if (!eMRRecordID) {
        // message.error('模板加载失败')
      }
      return;
    }
    let data = {
      // lockStatus为Y则为加锁
      params: [{
        patEMRRecordID: eMRRecordID,
        lockStatus: flag === 'patientRecords' ? 'Y' : undefined,
        uEMRRecLockPow: treeSelectData === 'forceUnlock' ? 'removeOtherLock' : undefined, // 强制解锁标志
      }]
    }
    $http.post('urlS', this, {
      code: '06050015',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let modifyParams = [{
            keys: 'isDeleteRecord',
            values: true
          }]
          let newPanes = this.modifyDataRelatedToMedicalRecords(modifyParams);
          if (flag === 'patientRecords') { // 加载患者病历
            this.setState({ panes: newPanes }, () => { // 加载已保存的患者病历模板可以删除
              this.newLoadingMedicalRecords(treeSelectData, obj, flag);
            })
          }
          if (treeSelectData === 'forceUnlock') { // 强制解锁
            let oldModalRowData = this.getDataRelatedToMedicalRecords('modalRowData') ? this.getDataRelatedToMedicalRecords('modalRowData') : this.state.modalRowData;
            let oldTreeSelectData = this.getDataRelatedToMedicalRecords('treeSelectData') ? this.getDataRelatedToMedicalRecords('treeSelectData') : this.state.treeSelectData;
            modifyParams[0].values = false;
            this.setState({ panes: newPanes }, () => {
              this.getPatienHistoryData(oldTreeSelectData, oldModalRowData, oldModalRowData && oldModalRowData.flag ? oldModalRowData.flag : '')
            })
          }
        }
      }
    })
  })

  // 向外输出当前模板名称
  getTemplateDesc = () => {
    let { modalRowData } = this.state;
    return modalRowData && modalRowData.descripts ? modalRowData.descripts : '';
  }

  handlePreviewOk = () => {
    let { knowledgeNodeContent, knowledgeBaseTreeSelectData } = this.state;
    // console.log(knowledgeNodeContent, knowledgeBaseTreeSelectData)
    this.props.setKnowledgeBaseXMl(knowledgeNodeContent, knowledgeBaseTreeSelectData);
  }

  // 患者病历右键
  handleRecordsRightClick = ({ event, node }) => {
    let record = node.props && node.props.dataRef ? node.props.dataRef : {};
    // 当右键目录树类型为TEMPLATE并且progressID不等于存在并且不等于first（首程主节点）
    if (record && record.treeType === 'TEMPLATE' && !(record.progressID && record.progressID !== 'first')) {
      this.handleContextMenu(record, event);
    }
  }

  // 右键菜单事件
  handleContextMenu = (record, event) => {
    if (this.root)
      event.preventDefault()

    this.setState({ contextMenuData: record, menuVisible: true })

    // clientX/Y 获取到的是触发点相对于浏览器可视区域左上角距离
    const clickX = event.clientX
    const clickY = event.clientY
    // window.innerWidth/innerHeight 获取的是当前浏览器窗口的视口宽度/高度
    const screenW = window.innerWidth
    const screenH = window.innerHeight
    // 获取自定义菜单的宽度/高度
    const rootW = this.root.offsetWidth
    const rootH = this.root.offsetHeight

    // right为true，说明鼠标点击的位置到浏览器的右边界的宽度可以放下菜单。否则，菜单放到左边。
    // bottom为true，说明鼠标点击位置到浏览器的下边界的高度可以放下菜单。否则，菜单放到上边。
    const right = (screenW - clickX) > rootW
    const left = !right
    const bottom = (screenH - clickY) > rootH
    const top = !bottom

    if (right) {
      this.root.style.left = `${clickX}px`
    }

    if (left) {
      this.root.style.left = `${clickX - rootW}px`
    }

    if (bottom) {
      // console.log('bottom')
      this.root.style.top = `${clickY + 12}px`
    }
    if (top) {
      // console.log('top')
      this.root.style.top = `${clickY - rootH}px`
    }
  };

  // 切换病历tab
  handleRecordChange = activeKey => {
    let { panes } = this.state;
    let currenTabInfo = {}
    panes.map(item => {
      if (item.key == this.state.recordActiveKey)
        currenTabInfo = item
    })
    this.setState({ recordActiveKey: activeKey, templateID: currenTabInfo.templateID });
  }

  onEdit = (targetKey, action) => {
    if (action === 'remove') {
      this.handleRemoveRecordATab(targetKey)
    }
    // this[action](targetKey);
  };

  handleCaseTemplateRef = (ref, tabCaseTemplateChild) => {
    if (tabCaseTemplateChild) {
      this[tabCaseTemplateChild] = ref;
    } else {
      this.caseTemplateChild = ref;
    }
  }

  // 将ID中的||替换成_
  handleReplaceWithUnderline = (str) => {
    if (str && str.indexOf('||') !== -1) {
      return str.replace('||', '_');
    }
    return str;
  }

  // 添加tab
  handleAddTab = (obj, callback) => {
    const activeKey = obj && obj.ID && obj.treeType ? (obj.treeType + obj.ID) : (obj && obj.ID ? obj.ID : `newTab${this.newTabIndex++}`);
    let replaceActiveKey = this.handleReplaceWithUnderline(activeKey);
    let isExist = false;
    let panes = JSON.parse(JSON.stringify(this.state.panes));
    let maxOpenTablePanel = this.state.maxOpenTablePanel ? this.state.maxOpenTablePanel : 5; // 最大打开的病历页签数
    if (panes && panes.length > 0) {
      for (var i = 0; i < panes.length; i++) {
        let activeIndexKey = panes[i] && panes[i].ID && panes[i].treeType ? (panes[i].treeType + panes[i].ID) : (panes[i] && panes[i].ID ? panes[i].ID : `newTab${this.newTabIndex++}`)
        if (activeIndexKey === activeKey) {
          isExist = true;
          break;
        }
      }
    }
    // console.log(panes, activeKey)
    if (isExist) { // 判断是否已经存在该页签，存在则直接跳转，不存在则创建
      this.setState({ recordActiveKey: replaceActiveKey }, () => {
        if (callback) {
          callback();
        }
      });
    } else {
      if ((panes.length + 1) > maxOpenTablePanel) {
        message.error('为了不影响病历程序运行效率，同时打开的病历页签不能超过' + maxOpenTablePanel + '个。');
        return;
      }
      panes.push({
        ID: obj && obj.ID ? obj.ID : '',
        treeType: obj && obj.treeType ? obj.treeType : '',
        closable: obj && obj.closable ? obj.closable : 'Y',
        title: obj && obj.descripts ? obj.descripts : '病历',
        key: replaceActiveKey,
        wTempCataID: obj && obj.wTempCataID ? obj.wTempCataID : '',
        templateID: obj && obj.templateID ? obj.templateID : '',
        onRef: (ref) => this.handleCaseTemplateRef(ref, replaceActiveKey)
      });
      this.setState({ panes, recordActiveKey: replaceActiveKey }, () => {
        if (callback) {
          callback();
        }
      });
    }
  }

  // 删除病历页签
  handleRemoveRecordATab = targetKey => {
    let { recordActiveKey } = this.state;
    let oldModalRowData = this.getDataRelatedToMedicalRecords('modalRowData', targetKey);
    let lastIndex;
    this.state.panes.forEach((pane, i) => {
      if (pane.key === targetKey) {
        lastIndex = i - 1;
      }
    });
    const panes = this.state.panes.filter(pane => pane.key !== targetKey);
    if (panes.length && recordActiveKey === targetKey) {
      if (lastIndex >= 0) {
        recordActiveKey = panes[lastIndex].key;
      } else {
        recordActiveKey = panes[0].key;
      }
    }
    // console.log('panes', panes)
    this.setState({ panes, recordActiveKey }, () => {
      if (oldModalRowData && oldModalRowData.patEMRRecordID) {
        this.updateMedicalRecordLockStatus(oldModalRowData && oldModalRowData.patEMRRecordID ? oldModalRowData.patEMRRecordID : ''); // 解锁
      }
    });
  };

  // 获取当前病历所在tab所需的数据
  getDataRelatedToMedicalRecords = (param, targetKey) => {
    let { panes, recordActiveKey } = this.state;
    // tabs所对应的key值 不传则默认当前选中的key值
    let key = targetKey ? targetKey : recordActiveKey;
    // console.log('panes', panes)
    if (panes && panes.length > 0) {
      for (var i = 0; i < panes.length; i++) {
        if (panes[i].key === key) {
          return panes[i][param];
        }
      }
    } else {
      return ''
    }
  }

  // 修改当前病历所在tab的数据
  modifyDataRelatedToMedicalRecords = (params) => {
    let { recordActiveKey } = this.state;
    let newPanes = JSON.parse(JSON.stringify(this.state.panes));
    for (var i = 0; i < newPanes.length; i++) {
      if (newPanes[i].key === recordActiveKey) {
        for (var j = 0; j < params.length; j++) {
          newPanes[i][params[j].keys] = params[j].values;
        }
        break;
      }
    }
    return newPanes;
  }

  // 回退
  handleBackOff = () => {
    let { recordData, contextMenuData } = this.state;
    let data = {
      params: [{
        recordID: contextMenuData && contextMenuData.patEMRRecordID ? contextMenuData.patEMRRecordID : '',
        statusCode: 'R',
        // type: 'ALL',
        admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ''),
      }]
    }
    $http.post('urlS', this, {
      code: '06050022',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          message.success(res && res.errorMessage ? res.errorMessage : '回退成功');
          this.getTreeData('patientRecords'); // 保存成功之后重新加载患者病历  
        }
      }
    })
  }

  // 跳转回引用界面
  handleGoToQuote = (defaultSelectedKeys) => {
    let treeSelectData = this.getDataRelatedToMedicalRecords('treeSelectData') ? this.getDataRelatedToMedicalRecords('treeSelectData') : this.state.treeSelectData;
    this.medicalRecordTemplate && this.medicalRecordTemplate.modifyVisible(true, treeSelectData, this.state.modalTemplateData, defaultSelectedKeys);
  }

  // 获取质控表单数据
  getQualityControlFormData = async () => {
    try {
      let res = await React.$asyncPost(this, '06090001');
      let qualityControlFormData = res?.data || res?.result || [];
      qualityControlFormData = qualityControlFormData && Array.isArray(qualityControlFormData) ? qualityControlFormData.map(item => {
        return {
          ...item,
          dataIndex: item?.code || '',
          typeCode: item?.value || 'TextArea',
          title: item?.descripts || '',
        }
      }) : [];
      this.setState({ qualityControlFormData, copyQualityControlFormData: JSON.parse(JSON.stringify(qualityControlFormData)) });
    } catch (error) {
      console.log(error)
    }
  }

  // 打开质控弹窗
  modifyQualityControlVisible = (visible) => {
    this.qualityControlRef && this.qualityControlRef.modifyVisible(visible);
  }

  // 查看点评内容
  handleViewQualityControl = async () => {
    try {
      const { recordData, copyQualityControlFormData } = this.state;
      let data = {
        params: [{
          admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ''),
        }]
      }
      let res = await React.$asyncPost(this, '06090003', data);
      let SDArr = res.result?.SDArr || [];
      let MRArr = res.result?.MRArr || [];
      let qualityControlFormData = [];
      let qualityControlRowData = {};
      if (SDArr && SDArr.length > 0 && MRArr && MRArr.length > 0) {
        qualityControlFormData.push({
          dataIndex: 'SD_commentUser',
          typeCode: 'Text',
          title: '',
          col: 12,
          labelCol: 5,
          wrapperCol: 18
        }, {
          dataIndex: 'MR_commentUser',
          typeCode: 'Text',
          title: '',
          col: 12,
          labelCol: 5,
          wrapperCol: 18
        });
        qualityControlRowData.SD_commentUser = res.result?.SDUser || '';
        qualityControlRowData.MR_commentUser = res.result?.MRUser || '';
      } else {
        qualityControlFormData.push({
          dataIndex: 'commentUser',
          typeCode: 'Text',
          title: '',
        });
        qualityControlRowData.commentUser = res.result?.SDUser || res.result?.MRUser || '';
      }
      for (let i = 0; i < copyQualityControlFormData.length; i++) {
        let currentItem = copyQualityControlFormData[i];
        let currentDataIndex = currentItem?.code || '';
        if (SDArr && SDArr.length > 0 && MRArr && MRArr.length > 0) {
          let SD_recordData = Util.returnDataCccordingToAttributes(SDArr, currentItem?.id || '', 'itemID');
          let MR_recordData = Util.returnDataCccordingToAttributes(MRArr, currentItem?.id || '', 'itemID');
          qualityControlRowData['SD_' + currentDataIndex] = SD_recordData?.comment || '';
          qualityControlRowData['MR_' + currentDataIndex] = MR_recordData?.comment || '';
          qualityControlFormData.push({
            ...currentItem,
            dataIndex: 'SD_' + currentDataIndex,
            disabled: SD_recordData.editFlag === 'Y' ? 'N' : 'Y',
            col: 12,
            labelCol: 5,
            wrapperCol: 18
          }, {
            ...currentItem,
            dataIndex: 'MR_' + currentDataIndex,
            disabled: MR_recordData.editFlag === 'Y' ? 'N' : 'Y',
            col: 12,
            labelCol: 5,
            wrapperCol: 18
          })
        } else {
          let recordData = Util.returnDataCccordingToAttributes(SDArr && SDArr.length > 0 ? SDArr : MRArr, currentItem?.id || '', 'itemID');
          qualityControlRowData[currentDataIndex] = recordData?.comment || '';
          qualityControlFormData.push({
            ...currentItem,
            disabled: recordData?.editFlag === 'Y' ? 'N' : 'Y',
          })
        }
      }
      this.setState({ qualityControlFormData, qualityControlRowData, oualityControlType: (MRArr && MRArr.length > 0 && SDArr && SDArr.length > 0) ? 'view' : 'add' }, () => {
        this.modifyQualityControlVisible(true);
      })
    } catch (error) {
      console.log(error)
    }
  }

  render() {
    let { spinLoading, treeData, showValidateResult, commitFlag, templateName, autoExpandParent, expandedKeys, selectedKeys, loadingTitle, menuVisible, recordActiveKey, panes, commitBtnDesc, contextMenuData,
      isHasDeletedRecord, historyAdmID, qualityControlFormData, qualityControlRowData, oualityControlType, EMRQCFlag
    } = this.state;

    // 获取当前病历所在的tabs的相对数据
    let eMRRecordID = this.getDataRelatedToMedicalRecords('eMRRecordID') ? this.getDataRelatedToMedicalRecords('eMRRecordID') : this.state.eMRRecordID;
    let modalRowData = this.getDataRelatedToMedicalRecords('modalRowData') ? this.getDataRelatedToMedicalRecords('modalRowData') : this.state.modalRowData;
    let treeSelectData = this.getDataRelatedToMedicalRecords('treeSelectData') ? this.getDataRelatedToMedicalRecords('treeSelectData') : this.state.treeSelectData;
    let isDelete = this.getDataRelatedToMedicalRecords('isDeleteRecord') ? this.getDataRelatedToMedicalRecords('isDeleteRecord') : false;
    let isUnlocking = this.getDataRelatedToMedicalRecords('isUnlocking') !== undefined || this.getDataRelatedToMedicalRecords('isUnlocking') !== '' ? this.getDataRelatedToMedicalRecords('isUnlocking') : true;
    let param = {
      isInsert: 'hidden',
      formView: 'Normal',
      isFont: true,
      isAllElection: true,
      isClearFormat: true,
      isSetTemplateSize: true,
      isSaveAnother: true,
      headerFooterEditable: 'noEditable',
      setChapter: 'show',
      isDelete, // 删除按钮操作状态
      isHasDeletedRecord, // 撤销删除
      isUnlocking, // 解锁按钮操作状态
      isBindingKnowledgeBase: false,
      showValidateResult,
      prCont: this.props.prCont && this.props.prCont === 'N' ? false : true,
      comments: true,
      prClose: true,
      prTinue: true,
      prImport: true,
      // self: true,
      original: false,
      self: false,
      addRow: true,
      isShear: true,
      // isPaste: true,
      isReload: false,
      isBasicOperation: this.props.isBasicOperation ? this.props.isBasicOperation : false
    }

    const vCursor = this.state.isVResize ? 'col-resize' : 'default';
    const vColor = this.state.isVResize ? '#ddd' : 'rgba(240, 242, 245, 1)';

    return (
      <Spin tip={loadingTitle} spinning={spinLoading} delay={300} style={{ height: '100%' }}>
        <div style={{ height: this.props.clpHeader ? this.props.clpHeader : store.getState().tableHeight.y + 158 }} className="case-information-page case-information-page-hospital">
          <div style={{ height: '6px', background: 'rgba(240, 242, 245, 1)', display: this.props.clpHeader ? 'none' : 'block' }}></div>
          <div style={{ width: "260px", height: 'calc(100% - 6px)', display: 'inline-block', overflow: 'hidden', paddingRight: '6px', position: 'relative' }}>
            <div style={{ width: '100%', padding: "8px 8px 0" }}>
              <Input style={{ width: this.props && this.props.caseInformationPageTabs && this.props.caseInformationPageTabs === "N" ? "100%" : 'calc(100% - 83px)' }} value={templateName} onChange={this.handleTemplateNameChange} placeholder={this.setMessage("CaseInformationPageTemplate_name_query", "descripts", "请输入模板名称查询")} />
              {this.props && this.props.caseInformationPageTabs && this.props.caseInformationPageTabs === "N" ? "" : <Popconfirm title={<div style={{ color: 'red' }}><div>确定一键提交患者病历???</div><div>一键提交后患者所有病历均不可修改!!</div></div>}
                onConfirm={this.commitPatEMR.bind(this, "ALL")}
                okText="确认提交">
                <Button style={{ marginLeft: "12px", padding: '0', width: '70px' }} type="primary" disabled={commitFlag === "Y" ? true : false}>{commitBtnDesc ? commitBtnDesc : "一键提交"}</Button>
              </Popconfirm>}
            </div>
            <div style={{ fontWeight: 'normal', fontSize: '13px', marginTop: '6px', paddingLeft: '12px' }}>
              {EMRQCFlag === 'Y' ? <span>病历被退回！<span className="span" onClick={this.handleViewQualityControl}>点击查看退回原因</span></span> : ''}
            </div>
            <div
              style={{
                height: this.props.clpHeader ? '69vh' : (EMRQCFlag === 'Y' ? 'calc(100% - 68px)' : 'calc(100% - 42px)'),
                paddingRight: '4px'
              }}
            >
              <Tree
                showIcon
                className="scroll-bar-style"
                expandedKeys={expandedKeys}
                selectedKeys={selectedKeys}
                autoExpandParent={autoExpandParent}
                style={{ height: '100%', paddingRight: '6px', overflow: 'auto', }}
                onExpand={this.handleRecordsExpand}
                onSelect={this.handleRecordsSelect}
                onDoubleClick={this.handleRecordsDoubleClickTreeNodes}
                onRightClick={this.handleRecordsRightClick}
              >
                {this.renderTreeNodes(treeData)}
              </Tree>
            </div>
            {/* componentSource -- 组件来源 */}
            <div ref={(ref) => { this.root = ref }} className="contextMenu-wrap" style={{ visibility: menuVisible ? 'visible' : 'hidden' }}>
              {this.props.componentSource && this.props.componentSource === "PreviewOfPatientsMedicalRecord" ? "" : <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={this.deletePatientHistory}>
                <div className="contextMenu-option"
                >删除患者病历</div>
              </Popconfirm>}
              {this.props.componentSource && this.props.componentSource === "PreviewOfPatientsMedicalRecord" ? "" : <Popconfirm title="提交后不可再修改病历，你确定要提交吗?" onConfirm={this.commitPatEMR.bind(this, "")}>
                <div className="contextMenu-option"
                >提交病历</div>
              </Popconfirm>}
              {this.props.componentSource && this.props.componentSource === "PreviewOfPatientsMedicalRecord" && contextMenuData && contextMenuData.submitBackFlag && contextMenuData.submitBackFlag === "Y" ? <Popconfirm title="该操作会将病历回退给医生，确定要回退吗?" onConfirm={this.handleBackOff}>
                <div className="contextMenu-option"
                >回退</div>
              </Popconfirm> : ""}
            </div>

            <div style={{ position: 'absolute', right: '0', top: '0', width: '6px', background: 'rgba(240, 242, 245, 1)', height: '100%' }}></div>
          </div>
          <div style={{ width: "calc(100% - 260px)", position: 'relative', height: 'calc(100% - 6px)', overflow: "hidden", display: "inline-block" }}
            onMouseUp={this.stopResize} onMouseLeave={this.stopResize}
          >
            <div id='v_resize_container' style={{ width: "100%", position: "absolute", left: 0, top: 0, right: 0, bottom: 0, height: '100%' }} onMouseMove={this.vResizeOver}>
              <div id='h_resize_container' style={{ width: this.props && this.props.caseInformationPageTabs && this.props.caseInformationPageTabs === "N" ? "100%" : (this.state.hideTabs ? "calc(100% - 40px)" : this.state.vNum), cursor: vCursor, height: '100%', float: "left" }} onMouseMove={this.hResizeOver}>
                <Tabs
                  hideAdd
                  onChange={this.handleRecordChange}
                  activeKey={recordActiveKey}
                  type="editable-card"
                  style={{ height: "100%" }}
                  className="record-tabs"
                  onEdit={this.onEdit}
                >
                  {panes && panes.map(pane => (
                    <TabPane tab={pane.title} key={pane.key} style={{ height: recordActiveKey === pane.key ? "100%" : "0px" }} closable={pane && pane.closable && pane.closable === 'N' ? false : true}>
                      <div style={{ height: "100%" }}>
                        <ElectronicCaseTemplate
                          pasteRemoveSpaces="N" // 粘贴操作是否去除空格标志
                          saveBeforePrintingFlag="Y" // 打印前是否需要保存标志
                          param={param}
                          onRef={pane && pane.onRef ? pane.onRef : this.handleCaseTemplateRef}
                          handleSave={this.handleSave}
                          undoDeleted={this.undoDeleted}
                          // handleDelete={this.deletePatientHistory}
                          getKnowledgeBaseTreeData={this.getChildKnowledgeBaseTreeData}
                          handleExampleTemplate={this.handleExampleTemplate}
                          handleExampleknow={this.handleExampleknow}
                          handleReload={this.handleOk}
                          handleOnReload={modalRowData && modalRowData.ID ? () => this.getPatienHistoryData(treeSelectData, modalRowData, modalRowData && modalRowData.flag ? modalRowData.flag : "") : ""} // goDoctorAdviceStepPage
                          editorID={this.props.editorID ? (this.props.editorID + pane && pane.key ? pane.key : "") : ("CIHWriterControl" + pane && pane.key ? pane.key : "")}
                          handleSaveTheInsertedCourse={this.handleSaveTheInsertedCourse} // 保存插入的病程记录
                          updateMedicalRecordLockStatus={() => this.updateMedicalRecordLockStatus(modalRowData && modalRowData.patEMRRecordID ? modalRowData.patEMRRecordID : eMRRecordID, "forceUnlock")}
                        />
                      </div>
                    </TabPane>
                  ))}
                </Tabs>
              </div>
              {this.state.hideTabs ? '' : (
                <div
                  className="v-resize"
                  draggable={false}
                  style={{ left: this.state.vNum, backgroundColor: vColor, display: this.props && this.props.caseInformationPageTabs && this.props.caseInformationPageTabs === 'N' ? 'none' : 'block' }}
                  onMouseDown={this.vResizeDown}
                />
              )}
              <div style={{ marginLeft: this.state.vNum + 6, cursor: vCursor, height: '100%', display: !this.state.hideTabs ? (this.props && this.props.caseInformationPageTabs && this.props.caseInformationPageTabs === 'N' ? 'none' : 'block') : 'none' }}>
                <CaseInformationPageTabs
                  historyAdmID={historyAdmID}
                  handleQuote={this.handleQuote} setKnowledgeBaseXMl={this.setKnowledgeBaseXMl} onRef={this.handleCaseInformationRef}
                  modalRowData={modalRowData} treeSelectData={treeSelectData} compileVNum={this.compileVNum}
                  knowledgeBaseAssignment={this.knowledgeBaseAssignment}
                  hideTabs={this.hideModule.bind(this)}
                />
              </div>
              {this.state.hideTabs ? (
                <Card
                  hoverable={true}
                  style={{
                    width: '30px', height: '100%', float: 'left', background: '#f5f4f4', cursor: 'pointer', paddingTop: 200, textAlign: 'center'
                  }}
                  bodyStyle={{
                    padding: '6px'
                  }}
                  onClick={this.showModule.bind(this)}
                >
                  <div className='change-card-icon-show'><Tooltip title="点击此处显示引用页签">
                    <Icon type='double-left' style={{ fontSize: '18px' }} /></Tooltip></div>点击此处显示引用页签
                </Card>
              ) : ''}
            </div>
          </div>

          {/* 另存为范例病例 */}
          <AddSampleTemplate handleGoToQuote={this.handleGoToQuote} onRef={ref => this.sampleTemplate = ref} />

          {/* 病历模板选择 */}
          <MedicalRecordTemplateSelection handleModify={this.handleExampleTemplate} handleOk={this.handleOk} onRef={ref => this.medicalRecordTemplate = ref} />

          <ColumnAuthoritysModel
            clientWidth="800px"
            compontName="CaseInformationPageHospital"
            configType="C"
            onRef={this.onMainColumnRef}
            reloadData={this.getChineseAndEnglishData}
          />
        </div>

        {/* 主表新增弹窗 */}
        <PublicModalFormHooks
          isFooter="N"
          title="病历质控"
          width={oualityControlType === 'view' ? '1200px' : '800px'}
          onRef={ref => this.qualityControlRef = ref}
          formData={qualityControlFormData}
          rowData={qualityControlRowData}
          formItemCol={{ labelCol: 5, wrapperCol: 16, col: 24 }}
        />
      </Spin >
    )
  }
};

const CaseInformationPageExampleCaseForm = Form.create()(CaseInformationPageExampleCase);
export default CaseInformationPageExampleCaseForm;